<template>
	<view class="content">
		<view class="app-title ac">
			<view class="fl" @click="back">
				<image class="back" src="/static/img/back.png"></image>
			</view>
			分配设备
		</view>
		<!-- <view style="height: 140upx;"></view> -->
		<view class="line-select">
			<view class="leaderClass">

				<u-cell-item required title="工单负责人" :value="woLeader.woLeaderName == '' ? '请选择' : woLeader.woLeaderName"
					@click="
				selece_type='leader';
				show_picker = true;
				columns = leaderOptions;
				label_name = 'name';
				value_name = 'idK';">
				</u-cell-item>
			</view>
			<scroll-view scroll-y="true" class="scroll-Y">
				<u-card padding="20" margin="10px" :title="item.taskType +' | '+ item.taskYearName"
					v-for="(item, index) in taskList" :key="item.idK">
					<view slot="head" class="card_head">
						<view class='title'> {{item.taskType +' | '+ item.taskYearName}}</view>
						<view>
							<u-button type="primary" size="mini" :plain="true" @click="add(index)">新增</u-button>
						</view>
					</view>
					<view class="body_box" slot="body">
						<u-swipe-action v-for="(deviceItem,index2) in item.assignDevice" :key="deviceItem.id"
							:show="deviceItem.show" :index="index2" @click="click" @open="open(index,index2)"
							:disabled="item.assignDevice.length==1" :options="options">
							<view class="cordClass">
								<u-cell-item required title="作业人" :value="deviceItem.userName" @click="
								deviceIndex = index2;
								taskIndex =index;
								selece_type='peopleName';
								showPeople();
							
								label_name = 'name';
								value_name = 'idK';">
								</u-cell-item>
								<u-cell-item title="设备:" :value="deviceItem.detailWorkEquName"
									@click=" deviceIndex = index2;taskIndex =index;  getEquList();deviceName=deviceItem.detailWorkEquName">
								</u-cell-item>
							</view>
							<u-line color="#ecf5ff" />
						</u-swipe-action>
					</view>
				</u-card>
			</scroll-view>
			<view class="footer">
				<u-button type="primary" size="medium" :ripple="true" @click="assignDevice">确认分派</u-button>
			</view>
		</view>
		<selectDevice v-show="show_device" :deviceName="deviceName" :device="optionEquName" @close="show_device = false"
			@setDevice="setDevice"></selectDevice>
		<u-select v-model="show_picker" :list="columns" label-name="name" value-name="idK" @confirm="onConfirm"
			@cancel="onCancel">
		</u-select>
	</view>
</template>

<script>
	import selectDevice from '../../components/myWork/viewWork/selectDevice.vue'
	import {

		WORK_CONTROLLER
	} from "../../api/pms";

	export default {
		props: {
			detailContent: {}
		},
		components: {
			selectDevice
		},
		data() {
			return {
				taskList: [],
				show_device: false,
				show_picker: false,
				selece_type: "",
				deviceName: '',
				optionEquName: '',
				columns: [],
				leaderOptions: [],
				taskIndex: "",
				deviceIndex: "",
				optionEquName: [], // 设备列表
				optionStation: [], //车站列表
				disabled: false,
				btnWidth: 180,
				show: false,
				woLeader: {
					woLeaderName: '',
					woLeaderId: "",

				},
				people: {
					name: [],
					id: []
				},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				woSn: '',
				filterPeople: [],
				taskDetailList: [],
				toolDetailList: [],
			}
		},
		async onLoad(options) {
			this.woSn = options.woSn;
			this.taskDetailList = options.taskListStr && JSON.parse(options.taskListStr) || [];
			this.toolDetailList = options.toolListStr && JSON.parse(options.toolListStr) || [];
			console.log(this.taskDetailList, 'taskDetailList');
			console.log(this.toolDetailList, 'toolDetailList');
		},
		mounted() {
			let task = this.$store.state.taskList && this.$store.state.taskList.taskName || [];
			this.taskList = task.map((item, index) => {
				return {
					...item,
					assignDevice: [{
						detailWorkId: item.taskName,
						idK: item.idK,
						userName: "",
						userId: "",
						detailWorkEquName: "",
						detailWorkEquIds: "",
						id: this.randomString()
					}]
				}
			})
			console.log('this.taskList',this.taskList)
			this.leaderOptions = this.$store.state.orderPeople
		},
		methods: {
			showPeople() {
				this.columns = this.leaderOptions
				this.show_picker = true
			},
			getAllPeople() {
				let people = [

				]
				let device = []
				this.taskList.forEach(item => {
					item.assignDevice.forEach(inItem => {
						let some = people.some(someItem => {
							return someItem.userName == inItem.userName
						})
						console.log('some--', some)
						if (!some) {
							people.push({
								userName: inItem.userName,
								userId: inItem.userId
							})
						}
						device.push({
							detailWorkId: inItem.idK,
							userName: inItem.userName,
							userId: inItem.userId,
							detailWorkEquName: inItem.detailWorkEquName,
							detailWorkEquIds: inItem.detailWorkEquIds,

						})
					})
				})
				console.log('people', people)
				let peopleName = people.map(item => {
					return item.userName
				})
				let peopleId = people.map(item => {
					return item.userId
				})
				return {
					peopleName,
					peopleId,
					device
				}
			},
			assignDevice() {
				
				let status = true
				this.taskList.forEach(item => {
					let assignDevice = item.assignDevice
					let some = assignDevice.every(evItem => {
						return evItem.userName
					})
					if (!some) status = false
					console.log('some---', some)
				})
				if (!this.woLeader.woLeaderName) {
					uni.showToast({
						title: '工单负责人不能为空！',
						icon: 'none'
					})
					return
				}
				if (!status) {
					uni.showToast({
						title: '作业人不能为空！',
						icon: 'none'
					})
					return
				}
				console.log('this.taskList', this.taskList)
				let {
					peopleName,
					peopleId,
					device
				} = this.getAllPeople()
				let params = {
					// userIds: peopleId.toString(),
					// userName:peopleName.toString(),
					woSn: this.$store.state.taskList.woSn,
					workLeaderId: this.woLeader.woLeaderId,
					workLeaderName: this.woLeader.woLeaderName,
					deatailWorkList: device,
					pmsWoDetailedWorkDOList: this.taskDetailList,
					pmsWoToolsDOList: this.toolDetailList,
				}
				console.log('params',params)
				this.fetch(
					"post",
					this.$store.state.baseUrl + WORK_CONTROLLER.TASK_DISTRIBUTE, params, false
				).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: "分派成功",
							icon: "none",
						});
						this.back(12)
					}
				})
			},
			add(param) {
				console.log('增加------')
				this.taskIndex = param
				this.taskList[this.taskIndex].assignDevice.unshift({
					detailWorkId: this.taskList[this.taskIndex].taskName,
					idK: this.taskList[this.taskIndex].idK,
					userName: "",
					userId: "",
					detailWorkEquName: "",
					detailWorkEquIds: "",
					id: this.randomString()
				})
			},
			back(param) {
				if (param) {
					uni.navigateTo({
						url: `/pages/productCenter/list?typeid=2`
					});
				} else {

					let pages = getCurrentPages();
					let prevPage = pages[pages.length - 2]; //上一个页面
					prevPage.referce = true
					uni.navigateBack({
						delta: 1
					})

				}


				// uni.navigateBack()

				console.log('sssss------------')
			},
			click(index, index1) {
				if (index1 == 0) {
					this.taskList[this.taskIndex].assignDevice.splice(index, 1);
				}
			},
			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(index1, index) {
				this.deviceIndex = index;
				this.taskIndex = index1;
				// console.log(index1, index)
				// // 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// // 原本为'false'，再次设置为'false'会无效
				// this.taskList[this.taskIndex].assignDevice[index].show = true
				// this.taskList[this.taskIndex].assignDevice.map((val, idx) => {
				// 	if (index != idx) this.taskList[this.taskIndex].assignDevice[idx].show = false;
				// })
			},
			setDevice(obj) {
				let checkTask = this.taskList[this.taskIndex]
				let device = checkTask.assignDevice[this.deviceIndex]
				device.detailWorkEquName = obj.name.toString()
				device.detailWorkEquIds = obj.id.toString()
				
				this.show_device = false;
				
				console.log('obj',obj)
				console.log('this.taskList[this.taskIndex]',this.taskList[this.taskIndex])
			},
			onConfirm(item) {
				switch (this.selece_type) {
					case "peopleName":
						let checkTask = this.taskList[this.taskIndex]
						let device = checkTask.assignDevice[this.deviceIndex]
						device.userName = item[0].label
						device.userId = item[0].value
						break;
					case "leader":
						this.woLeader.woLeaderName = item[0].label
						this.woLeader.woLeaderId = item[0].value
						break;
				}

				this.onCancel();
			},
			onCancel() {
				this.show_picker = false;

			},
			async getEquList() {
				let editItem = this.taskList[this.taskIndex]
				console.log('editItem',editItem)
				if(editItem.equName&&editItem.equID){
					let  equName = editItem.equName.split(',')
					let equID = editItem.equID.split(',')
					console.log('equName',equName,equID)
					this.optionEquName=equName.map((item,index)=>{
						return {
							equname:item,
							idk:equID[index]
						}
					})
					console.log('this.optionEquName',this.optionEquName)
					editItem.assignDevice.forEach((item, index) => {
						if (index != this.deviceIndex && item.detailWorkEquIds) {
							this.optionEquName.forEach((items) => {
								if (item.detailWorkEquIds.split(',').includes(items.idk)) {
									items.disabled = true
								}
							})
						}
					})
					this.show_device = true;
					return 
				}
				await this.getTaskDetailAndStation()

				let code = this.optionStation.filter(
					(i) => i.stationId == editItem.taskLocation
				)[0]?.stationCode;
				this.fetch(
					"post",
					this.$store.state.baseUrl + WORK_CONTROLLER.POST_EQU_EQULIST, {
						equtype: editItem.equTypeID,
						station: code,
						page: 1,
						size: 9999999,
					}, false
				).then((res) => {
					if (res) {
						this.optionEquName =res?.data?.content;
						this.optionEquName = this.optionEquName ? this.reduceArray(this.optionEquName, "idk") :
							[];
						let checkTask =this.taskList[this.taskIndex]
						console.log('checkTask', checkTask)
						checkTask.assignDevice.forEach((item, index) => {
							if (index != this.deviceIndex && item.detailWorkEquIds) {
								this.optionEquName.forEach((items) => {
									if (item.detailWorkEquIds.split(',').includes(items.idk)) {
										items.disabled = true
									}
								})
							}
						})
						this.show_device = true;
					}
				})
			},
			/**
			 *  根据某一个任务id 获取 该任务的详情，设备类型，和地点。
			 */
			async getTaskDetailAndStation(param) {
				let editItem = this.taskList[this.taskIndex]
				await this.fetch(
					"GET",
					this.$store.state.baseUrl + WORK_CONTROLLER.GET_WORK_TASKORG, {
						idK: editItem.yearMonthId
					}, false
				).then((res) => {
					if (res?.success) {
						this.optionStation = res?.data?.taskStation.filter((i) => {
							return editItem.taskLocation?.includes(i.stationId);
						});

					}
				})


			},
			// 数组对象元素去重
			reduceArray(initialArr, attr) {
				// const uniqueArr = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
				let uniqueArr = initialArr.reduce((acc, obj) => {
					let existingObj = acc.find((item) => item[attr] === obj[attr]);
					if (!existingObj) {
						acc.push(obj);
					}
					return acc;
				}, []);
				return uniqueArr;
			},
			random(lower, upper) {
				return Math.floor(Math.random() * (upper - lower + 1)) + lower;
			},
			randomString() {
				let length = this.random(5, 6);
				const chars =
					"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_=-";
				let result = "";
				for (let i = length; i > 0; --i) {
					result += chars[Math.floor(Math.random() * chars.length)];
				}
				return result;

			}


		}
	}
</script>

<style scoped lang="less">
	.leaderClass {
		padding: 10px 10px 0;
	}

	.content {
		height: 100vh;
		width: 100%;
	}

	.body_box {
		background-color: #fafafa;
	}

	.u-cell {
		padding: 6px 10px !important;
	}

	.scroll-Y {
		flex: 1;
		height: 0;
	}

	.footer {
		text-align: center;
		padding: 10px;
	}

	/deep/.u-swipe-action {
		margin-bottom: 5px !important;
		border-radius: 5px;

	}

	/deep/.u-card__body {
		padding: 10px 0px !important;
	}

	.line-select {
		height: calc(100vh - 140rpx);
		display: flex;
		flex-direction: column;

		.cordClass {
			padding: 0px 5px;
		}


		.card_head {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;

			.title {
				font-weight: 600;
			}
		}
	}

	/deep/.u-cell_title {
		padding-left: 5px;
	}
</style>